import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import { ElMessage } from 'element-plus'
import { staticRoutes } from '@/router/routes'
import { requestLogin, requestUserInfo, requestLogout } from '@/api/userInfo'
import type { reqLoginParamType, reqUserInfoReturnType } from '@/api/userInfo'
import type { RouteRecordRaw } from 'vue-router';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

//state返回值的类型
export interface UserInfoStateType {
  token: string,
  userInfo: reqUserInfoReturnType,
  menuRoutes: RouteRecordRaw[]
}
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoStateType => ({
    token: getToken() as string,
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: '',
      avatar: ''
    },
    menuRoutes: staticRoutes
  }),

  actions: {
    //登录逻辑
    async login(loginParam: reqLoginParamType) {
      try {
        const result = await requestLogin(loginParam)
        this.token = result.token
        //token数据持久化
        setToken(this.token)
      } catch (e) {
        return Promise.reject(e)
      }
    },

    //获取用户信息逻辑
    async getInfo() {
      try {
        const result = await requestUserInfo()
        this.userInfo = result
      } catch (e) {
        return Promise.reject(e)
      }
    },

    //退出登录逻辑
    async logout() {
      try {
        await requestLogout()
        //清除token,清除userInfo
        this.reset()
      } catch (e) {
        return Promise.reject(e)
      }
    },

    reset() {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: ''
      }
    },
  },
});
